<template>
  <div
    :class="{
    'login-wrap': loginVisible,
    'register-warp': registerVisible,
  }"
  >
    <!-- 登录区域 -->
    <el-form
      class="login-container"
      v-show="loginVisible"
      :model="loginForm"
      :rules="loginFormRules"
      ref="loginFormRef"
      status-icon
    >
      <h1 class="title">用户登陆</h1>
      <el-form-item prop="userName">
        <el-input
          :prefix-icon="User"
          type="text"
          v-model="loginForm.userName"
          placeholder="用户账号(用户名/手机号)"
          @keyup.enter="doLogin(loginFormRef)"
        ></el-input>
      </el-form-item>
      <el-form-item prop="userPassword">
        <el-input
          :prefix-icon="Lock"
          type="password"
          v-model="loginForm.userPassword"
          placeholder="用户密码"
          show-password
          @keyup.enter="doLogin(loginFormRef)"
        ></el-input>
      </el-form-item>
      <el-form-item class="btns">
        <el-button type="primary" size="large" @click="doLogin(loginFormRef)"
          >登陆</el-button
        >
        <el-button type="info" size="large" @click="resetLogin(loginFormRef)"
          >重置</el-button
        >
      </el-form-item>
      <div class="other" style="justify-self: unset;">
        <el-link type="primary" @click="isLogin = !isLogin">注册账号</el-link>
        <el-link type="primary" @click="forgetPassword">忘记密码</el-link>
      </div>
    </el-form>

    <!-- 注册区域 -->
    <el-form
      class="register-container"
      v-show="registerVisible"
      :model="registerForm"
      :rules="registerFormRules"
      ref="registerFormRef"
      status-icon
    >
      <h1 class="title">用户注册</h1>
      <el-alert
        title="用户名和用户密码为必填，其它为选填"
        type="warning"
        show-icon
        :closable="false"
      >
      </el-alert>
      <el-form-item prop="userName">
        <el-input
          :prefix-icon="User"
          type="text"
          v-model="registerForm.userName"
          placeholder="用户名"
        ></el-input>
      </el-form-item>
      <el-form-item prop="userPassword">
        <el-input
          :prefix-icon="Lock"
          type="password"
          v-model="registerForm.userPassword"
          placeholder="用户密码"
          show-password
        ></el-input>
      </el-form-item>
      <el-form-item prop="checkPassword">
        <el-input
          :prefix-icon="Lock"
          type="password"
          v-model="registerForm.checkPassword"
          placeholder="确认密码"
          show-password
        ></el-input>
      </el-form-item>
      <el-form-item prop="userTel">
        <el-input
          :prefix-icon="Phone"
          v-model="registerForm.userTel"
          placeholder="用户手机号"
        ></el-input>
      </el-form-item>
      <el-form-item prop="userEmail">
        <el-input
          :prefix-icon="Message"
          v-model="registerForm.userEmail"
          placeholder="用户邮箱"
        ></el-input>
      </el-form-item>
      <el-form-item class="btns">
        <el-button
          type="primary"
          size="large"
          @click="doRegister(registerFormRef)"
          >注册</el-button
        >
        <el-button
          type="info"
          size="large"
          @click="resetRegister(registerFormRef)"
          >重置</el-button
        >
      </el-form-item>
      <el-row class="other">
        <el-link type="primary" @click="isLogin = !isLogin">返回登录</el-link>
      </el-row>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import store from '@/store';
import { User, Lock, Phone, Message } from '@element-plus/icons-vue'
import { FormInstance, FormRules, ElMessage } from 'element-plus'
import { watch, ref, getCurrentInstance, ComponentInternalInstance, reactive } from 'vue';
const { appContext } = getCurrentInstance() as ComponentInternalInstance;
const proxy = appContext.config.globalProperties;

// 账号验证
const checkUsername = (_: any, value: any, callback: any) => {
  const usernameReg = /^[\u0391-\uFFE5a-zA-Z0-9]{3,12}$/;
  if (!value) {
    return callback(new Error('请输入账号'));
  }
  setTimeout(() => {
    if (usernameReg.test(value)) {
      callback();
    } else {
      callback(new Error('长度在 3 到 12 个字符'));
    }
  }, 100);
};
// 电话号码验证
const checkPhone = (_: any, value: any, callback: any) => {
  const phoneReg = /^1[3|4|5|7|8][0-9]{9}$/;
  if (value === '') {
    return callback();
    //return callback(new Error('电话号码不能为空'));
  }
  setTimeout(() => {
    if (!Number.isInteger(+value)) {
      callback(new Error('请输入数字值'));
    } else {
      if (phoneReg.test(value)) {
        callback();
      } else {
        callback(new Error('电话号码格式不正确'));
      }
    }
  }, 100);
};
// 密码验证
let checkPassword = (_: any, value: any, callback: any) => {
  let passwordReg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9a-zA-Z]{6,16}$/;
  if (!value) {
    return callback(new Error('请输入密码'));
  }
  setTimeout(() => {
    if (passwordReg.test(value)) {
      callback();
    } else {
      callback(new Error('密码必须为6~16位数字+字母组合'));
    }
  }, 100);
};
// 再次确认密码验证
let checkPassword2 = (_: any, value: any, callback: any) => {
  if (!registerForm.userPassword)
    callback(new Error('请先输入新密码'));
  if (value === '') {
    callback(new Error('请再次输入密码'));
  } else if (value !== registerForm.userPassword) {
    callback(new Error('两次输入密码不一致!'));
  } else {
    callback();
  }
};
// 邮箱验证
let checkEmail = (_: any, value: any, callback: any) => {
  const emailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
  if (!value) {
    callback();
    // return callback(new Error('邮箱不能为空'));
  }
  setTimeout(() => {
    if (emailReg.test(value)) {
      callback();
    } else {
      callback(new Error('请输入正确的邮箱格式'));
    }
  }, 100);
};

const loginFormRef = ref<FormInstance>()
// 登录数据
interface LoginForm {
  userName: String
  userPassword: String
}
const loginForm = reactive<LoginForm>({
  userName: '',
  userPassword: '',
})
// 登录表单验证
const loginFormRules = reactive<FormRules<LoginForm>>({
  userName: [{ validator: checkUsername }],
  userPassword: [{ validator: checkPassword }],
})

const registerFormRef = ref<FormInstance>()
// 注册数据
interface RegisterForm {
  userName: String
  userPassword: String
  checkPassword: String
  userTel: String
  userEmail: String
}
const registerForm = reactive<RegisterForm>({
  userName: '',
  userPassword: '',
  checkPassword: '',
  userTel: '',
  userEmail: '',
})
// 注册表单验证
const registerFormRules = reactive<FormRules<RegisterForm>>({
  userName: [{ validator: checkUsername }],
  userPassword: [{ validator: checkPassword }],
  checkPassword: [{ validator: checkPassword2 }],
  userTel: [{ validator: checkPhone }],
  userEmail: [{ validator: checkEmail }],
})

// 登录窗口是否可见
const loginVisible = ref(true)

// 注册窗口是否可见
const registerVisible = ref(false)

// true为用户登录，false为用户注册
const isLogin = ref(true)

// mapActions('userInf', ['getUserInfo']),

// 点击按钮后登录
function doLogin(formEl: FormInstance | undefined) {
  if (!formEl) return;
  formEl.validate((valid: any) => {
    if (!valid) return;
    proxy.$request.account.login(loginForm).then((res: any) => {
      proxy.$storage.setItem('userInfo', { ...res.data });
      // this.getUserInfo({ data: res.data.userId });
      store.dispatch('userInf/getUserInfo', { data: res.data.userId })
      ElMessage({
        message: '登录成功',
        type: 'success',
        duration: 1000,
      });
      proxy.$storage.setItem('activePath', 'home');
      proxy.$router.push('/home');
    });
  });
};

// 重置登录数据
function resetLogin(formEl: FormInstance | undefined) {
  if (!formEl) return;
  formEl.resetFields();
  setTimeout(() => {
    formEl.clearValidate();
  }, 100);
};

// 重置注册数据
function resetRegister(formEl: FormInstance | undefined) {
  if (!formEl) return
  formEl.resetFields();
  setTimeout(() => {
    formEl.clearValidate();
  }, 100);
};

// 点击按钮后注册
function doRegister(formEl: FormInstance | undefined) {
  if (!formEl) return;
  formEl.validate((valid: any) => {
    if (!valid) return;
    if (registerForm.userEmail || registerForm.userTel) {
      proxy.$request.account.checkUserInf({
        userEmail: registerForm.userEmail,
        userTel: registerForm.userTel,
      });
    }
    proxy.$request.account.register(registerForm).then(() => {
      ElMessage.success('注册成功');
      resetRegister(formEl);
      isLogin.value = true;
    });
  });
};

// 忘记密码
function forgetPassword() {
  ElMessage.warning('还没有开发噢~~');
};

watch(isLogin, (newValue) => {
  resetLogin(loginFormRef.value);
  resetRegister(registerFormRef.value);
  registerVisible.value = !newValue;
  loginVisible.value = newValue;
});
</script>

<style lang="less" scoped>
.login-wrap,
.register-warp {
  box-sizing: border-box;
  width: 100vw;
  height: 100%;
  background-image: url(@/assets/imgs/bg_login.png);
  background-repeat: no-repeat;
  background-size: cover;
}

.login-wrap {
  padding-top: 10%;
}

.register-warp {
  padding-top: 4%;
}

.register-container,
.login-container {
  border-radius: 10px;
  margin: 0px auto;
  width: 380px;
  padding: 30px 35px 15px 35px;
  background-color: #fff;
  border: 1px solid #eaeaea;
  text-align: left;
  box-shadow: 0 0 20px 2px rgba(0, 0, 0, 0.3);

  .title {
    margin: 0px auto 45px auto;
    text-align: center;
    color: #505458;
    font-size: 32px;
  }

  .btns {
    display: flex;
    justify-content: flex-end;
    // background-color: blue;
  }

  .other {
    text-align: center;
    justify-self: unset;
  }


  .el-link {
    margin: 0 10px;
  }
}

.login-container{
  /deep/ .el-form-item:nth-child(4) .el-form-item__content{
    flex: unset
  }
}

.register-container {
  .title {
    margin-bottom: 20px;
  }

  .el-alert {
    margin-bottom: 10px;
  }

  /deep/ .el-form-item:nth-child(8) .el-form-item__content{
    flex: unset
  }

  .other {
    display: flex;
    justify-content: flex-start;
  }
}
</style>
